﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace SapConnection
{
    public static class Con
    {
        public static string CreateLead(string msg)
        {
            string serviceUrl = "http://p138.coil.sap.com:8080/sap/opu/sdata/sap/ZCRM_LEAD";
            ZCRM_LEAD.ZCRM_LEAD service = new ZCRM_LEAD.ZCRM_LEAD(new Uri(serviceUrl));
            service.Credentials = new NetworkCredential("proen", "invent1");

            ZCRM_LEAD.zxact_lead l = new ZCRM_LEAD.zxact_lead
            {
                description = msg,
                long_text = msg,
                scheme_agency_id = "",
                scheme_id = "",
                value = ""
            };

            service.AddTozxact_leadCollection(l);

            try
            {
                var res = service.SaveChanges();
                return l.value;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);

                return null;
            }
        }

        public static void CreateSubscription(string guid)
        {
            string serviceUrl = "http://p138.coil.sap.com:8080/sap/opu/sdata/sap/ZCRM_LEAD";
            ZCRM_LEAD.ZCRM_LEAD service = new ZCRM_LEAD.ZCRM_LEAD(new Uri(serviceUrl));
            service.Credentials = new NetworkCredential("proen", "invent1");

            ZCRM_LEAD.Subscription s = new ZCRM_LEAD.Subscription
            {
                deliveryAddress = "http://lehavi.com:2057/Sap/LeadUpdated",
                scheme_agency_id = "",
                scheme_id = "",
                value = "",
                collection = "zxact_leadCollection",
                filter = "",//string.Format("value eq '{0}' and scheme_id eq '{1}' and scheme_agency_id eq '{2}'", guid, "ZXACT_LEAD", "CR7_800"),
                select = "*"
            };

            service.AddToSubscriptionCollection(s);

            try
            {
                var res = service.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        public static ZCRM_LEAD.zxact_lead GetLead(string guid)
        {
            string serviceUrl = "http://p138.coil.sap.com:8080/sap/opu/sdata/sap/ZCRM_LEAD";
            ZCRM_LEAD.ZCRM_LEAD service = new ZCRM_LEAD.ZCRM_LEAD(new Uri(serviceUrl));
            service.Credentials = new NetworkCredential("proen", "invent1");

            var lead = (from ZCRM_LEAD.zxact_lead l in service.zxact_leadCollection
                        where (l.value == guid && l.scheme_id == "ZXACT_LEAD"
                        && l.scheme_agency_id == "CR7_800")
                        select l).FirstOrDefault();

            return lead;
        }

    }
}
